package com.fxsh168.server.fragments;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.fxsh168.server.activity.BindAcountActivity;
import com.fxsh168.server.activity.BindKaActivity;
import com.fxsh168.server.activity.KehuPopupWindow;
import com.fxsh168.server.activity.LoginActivity;
import com.fxsh168.server.activity.SoldCenterActivity;
import com.fxsh168.server.activity.TransactionRecordActivity;
import com.fxsh168.server.base.BaseFragment;
import com.fxsh168.server.entitys.MyMsgQREntity;
import com.fxsh168.server.otherviews.banner.AdvertisementActivity;
import com.fxsh168.server.otherviews.banner.AutoPlayInfo;
import com.fxsh168.server.R;
import com.fxsh168.server.activity.BalanceActivity;
import com.fxsh168.server.activity.SpeakCenterActivity;
import com.fxsh168.server.activity.MyInfoActivity;
import com.fxsh168.server.activity.SettingActivity;
import com.fxsh168.server.interfaces.Constant;
import com.fxsh168.server.entitys.DialPhoneEntity;
import com.fxsh168.server.entitys.IndexShowImgEntity1;
import com.fxsh168.server.entitys.PersonInfoEntity;
import com.fxsh168.server.otherviews.banner.AutoPlayingViewPager;
import com.fxsh168.server.utils.CircleImageView;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

import static android.content.Context.MODE_PRIVATE;

public class PersonFragment extends BaseFragment implements View.OnClickListener {
    TableRow tabSetting, tabCenterTell, tabKeFu, tabIncome, tabBlance, tabBindAcount, tabChangeInfo;
    TextView mNickName, msgContentView;
    CircleImageView mBtnHead;
    RelativeLayout re_message;
    KehuPopupWindow menuWindowPerKefu;
    private String mPhone, token, callPhoneCur, photoPath;
    private List dataPerMsg0;
    private AlertDialog dialogPerMsg;
    private PersonInfoEntity.DataBean data;
    //    广告
    AutoPlayingViewPager mAutoPlayingViewPager;
    private String[] imageUrl, imageTitle, links;
    private List<AutoPlayInfo> mAutoPlayInfoList;
    ArrayList<String> indexImgPathLists;
    String ids;
    private SharedPreferences sp;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_person, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        indexImgPathLists = new ArrayList<>();
        mAutoPlayingViewPager = (AutoPlayingViewPager) view.findViewById(R.id.auto_play_viewpager);//首页viewpager
        tabSetting = (TableRow) view.findViewById(R.id.tabSetting);
        tabCenterTell = (TableRow) view.findViewById(R.id.tabCenterTell);
        tabKeFu = (TableRow) view.findViewById(R.id.tabKeFu);
        tabIncome = (TableRow) view.findViewById(R.id.tabIncome);
        tabBlance = (TableRow) view.findViewById(R.id.tabBlance);
        tabBindAcount = (TableRow) view.findViewById(R.id.tabBindAcount);
        tabChangeInfo = (TableRow) view.findViewById(R.id.tabChangeInfo);
        re_message = (RelativeLayout) view.findViewById(R.id.re_message);
        re_message.setOnClickListener(this);
        tabSetting.setOnClickListener(this);
        tabCenterTell.setOnClickListener(this);
        tabKeFu.setOnClickListener(this);
        tabIncome.setOnClickListener(this);
        tabBlance.setOnClickListener(this);
        tabBindAcount.setOnClickListener(this);
        tabChangeInfo.setOnClickListener(this);
        //获取登录Sharepreferrnces里面的数据
        sp = getActivity().getSharedPreferences(Constant.LOGINCLASS, MODE_PRIVATE);
        mPhone = sp.getString("mPhone", "");
        token = sp.getString("token", "");
        mNickName = (TextView) view.findViewById(R.id.nickName); //昵称
        mBtnHead = (CircleImageView) view.findViewById(R.id.btnHead);   //头像
        initSysMsg0();  //系统消息
        getDiaPhone();//获取电话号码
        //获取信息
        if (token != null && token.length() != 0) {
            initScan();
        }
        getIndexShowImg();
    }

    // 获取图片
    private void getIndexShowImg() {
        OkHttpUtils.post().url(Constant.BASEPATH2 + "/index.php?s=/App/App/ad")
                .addParams("com", 2 + "").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                IndexShowImgEntity1 indexShowImgEntity1 = new Gson().fromJson(response, IndexShowImgEntity1.class);
                if (indexShowImgEntity1 != null) {
                    String code = indexShowImgEntity1.getCode();
                    if (code.equals(200 + "")) {
                        Log.e("tag", "获取成功!" + response);
                        List<IndexShowImgEntity1.DataBean> data = indexShowImgEntity1.getData();
                        imageUrl = new String[data.size()];
                        imageTitle = new String[data.size()];
                        links = new String[data.size()];
                        for (int i = 0; i < data.size(); i++) {
                            IndexShowImgEntity1.DataBean dataBean = data.get(i);
                            imageUrl[i] = Constant.BASEPATH2 + dataBean.getPic();
                            links[i] = dataBean.getUrl();
                            imageTitle[i] = dataBean.getText();
                            Log.e("tag", "添加数组" + imageUrl[i]);
                        }
                        MyAsyncTask myAsyncTask = new MyAsyncTask(PersonFragment.this);
                        myAsyncTask.execute();
                    }
                }
            }
        });
    }


    static class MyAsyncTask extends AsyncTask<Void, Void, Void> {
        // 弱引用允许Activity被垃圾收集器清理 private final WeakReference<MyActivity> weakActivity;
        private final WeakReference<PersonFragment> personActivityWeakReference;

        MyAsyncTask(PersonFragment personActivity) {
            this.personActivityWeakReference = new WeakReference<PersonFragment>(personActivity);
        }

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
        @Override
        protected Void doInBackground(Void... params) {
            //模拟网络请求获取数据
            PersonFragment personActivity = personActivityWeakReference.get();
            if (personActivity == null || personActivity.isRemoving()) {

            } else {
                personActivity.mAutoPlayInfoList = changeAutoPlayInfoList(personActivity);
            }

            return null;
        }

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            Log.e("tag", "开始执行");
            //数据加载后更新UI
            PersonFragment personActivity = personActivityWeakReference.get();
            if (personActivity == null || personActivity.isRemoving()) {
                return;
            } else {
                personActivity.mAutoPlayingViewPager.initialize(personActivity.mAutoPlayInfoList).build();
                personActivity.mAutoPlayingViewPager.setOnPageItemClickListener(personActivity.onPageItemClickListener);
                personActivity.mAutoPlayingViewPager.startPlaying();
            }
        }
    }


    /**
     * 将数据转换为AutoPlayInfo形式
     */
    private static List<AutoPlayInfo> changeAutoPlayInfoList(PersonFragment personActivity) {
        List<AutoPlayInfo> autoPlayInfoList = new ArrayList<>();
        for (int i = 0; i < personActivity.imageUrl.length; i++) {
            AutoPlayInfo autoPlayInfo = new AutoPlayInfo();
            autoPlayInfo.setImageUrl(personActivity.imageUrl[i]);
            autoPlayInfo.setAdLinks(personActivity.links[i]);//无数据时不跳转
            autoPlayInfo.setTitle(personActivity.imageTitle[i]);
            autoPlayInfoList.add(autoPlayInfo);
        }
        return autoPlayInfoList;
    }


    private AutoPlayingViewPager.OnPageItemClickListener onPageItemClickListener = new AutoPlayingViewPager.OnPageItemClickListener() {
        @Override
        public void onPageItemClick(int position, String adLink) {
            // 直接返回链接,使用WebView加载
            //链接存在时才进行下一步操作,当然，这只是简单判断,这个字符串不是正确链接,则需要加上正则表达式判断。
            Intent intent = new Intent(PersonFragment.this.getActivity().getApplication(), AdvertisementActivity.class);
            intent.putExtra("linkPath", adLink);
            startActivity(intent);
        }
    };


    //获取电话号码
    private void getDiaPhone() {
        OkHttpUtils.post().url(Constant.DIAPHONEREQUESTPATH).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast("连接不上服务器!");
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    DialPhoneEntity dialPhoneEntity = new Gson().fromJson(response, DialPhoneEntity.class);
                    if (dialPhoneEntity != null) {
                        String code = dialPhoneEntity.getCode().trim();
                        if (code.equals(200 + "")) {
                            List<DialPhoneEntity.DataBean> data = dialPhoneEntity.getData();
                            if (data.size() > 0) {
                                DialPhoneEntity.DataBean dataBean = data.get(0);
                                if (dataBean != null) {
                                    Object call = dataBean.getCall();
                                    if (call != null) {
                                        //电话号码
                                        callPhoneCur = call.toString().trim();
                                        sp.edit().putString("kefuNumber",callPhoneCur).commit();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    //系统消息
    private void initSysMsg0() {
        OkHttpUtils.post().addParams("phone", mPhone).addParams("token", token)
                .url(Constant.PERSONMSGDRIVERREQUESTPATH).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast("连接不上服务器!");
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    MyMsgQREntity myMsgQREntity = new Gson().fromJson(response, MyMsgQREntity.class);
                    String code = myMsgQREntity.getCode().trim();
                    if (code.equals(200 + "")) {
                        dataPerMsg0 = myMsgQREntity.getData();
                        if (dataPerMsg0 instanceof List<?>) {
                            //用自定义dialog
                            AlertDialog.Builder builder = new AlertDialog.Builder(PersonFragment.this.getActivity());
                            View view1 = LayoutInflater.from(PersonFragment.this.getActivity()).inflate(R.layout.personmsgdialog_layout, null);//获取布局
                            builder.setView(view1);
                            msgContentView = (TextView) view1.findViewById(R.id.msgContentView);
                            //消息内容
                            if (dataPerMsg0.size() > 0) {
                                MyMsgQREntity.DataBean dataBean = (MyMsgQREntity.DataBean) dataPerMsg0.get(0);
                                String msgContent = dataBean.getContent().toString().trim();
                                msgContentView.setText(msgContent);
                            }
                            TextView btnOk = (TextView) view1.findViewById(R.id.btnOKPerMsg);//确定
                            btnOk.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (dataPerMsg0.size() > 0) {
                                        MyMsgQREntity.DataBean dataBean = (MyMsgQREntity.DataBean) dataPerMsg0.get(0);
                                        String idMsg0 = dataBean.getId().toString().trim();
                                        String msgContent = dataBean.getContent().toString().trim();
                                        msgContentView.setText(msgContent);
                                        //让对话框消失
                                        dialogPerMsg.dismiss();
                                    }
                                }
                            });
                            dialogPerMsg = builder.create();
                            dialogPerMsg.setCanceledOnTouchOutside(true);
                            dialogPerMsg.show();
                            WindowManager m = PersonFragment.this.getActivity().getWindowManager();
                            Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
                            WindowManager.LayoutParams p = dialogPerMsg.getWindow().getAttributes(); // 获取对话框当前的参数值
                            p.height = (int) (d.getHeight() * 0.215); // 高度设置为屏幕的0.6
                            p.width = (int) (d.getWidth() * 0.75); // 宽度设置为屏幕的0.95
                            dialogPerMsg.getWindow().setBackgroundDrawableResource(R.drawable.shapeindexexit);
                            dialogPerMsg.getWindow().setAttributes(p);
                        }
                    }
                }
            }
        });
    }

    //个人中心资料查看
    public void initScan() {
        OkHttpUtils.post().addParams("phone", mPhone).addParams("token", token)
                .url(Constant.GETPERSONINFOPATH).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast("连接不上服务器!");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("tag", "司机端个人资料" + response);
                if (response != null) {
                    PersonInfoEntity personInfoEntity = new Gson().fromJson(response, PersonInfoEntity.class);
                    if (personInfoEntity != null) {
                        String code = personInfoEntity.getCode().trim();
                        if (code.equals(200 + "")) {
                            data = personInfoEntity.getData();
                            ids = data.getId().toString().trim();
                            //头像路径
                            photoPath = data.getPhoto().toString().trim();
                            Message message = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("photoPath", photoPath);
                            message.setData(bundle);
                            handler.sendMessage(message);
                            String nickName = data.getUsername().toString().trim();//昵称
                            if (!nickName.equals("")) {
                                //设置昵称
                                mNickName.setText(nickName);
                            } else {
                                mNickName.setText("昵称");
                            }
                        }
                    }
                }
            }
        });

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            String czlphotoPath = bundle.getString("photoPath");
            //用Glide加载头像图片
            if (!TextUtils.isEmpty(czlphotoPath)) {
                Glide.with(PersonFragment.this.getActivity()).load(czlphotoPath).centerCrop().crossFade().into(mBtnHead);
            } else {
                mBtnHead.setImageResource(R.mipmap.waiting_head);//图片为空头像设置为默认图片
                mBtnHead.setFocusable(true);
            }
        }
    };

    //    判断做登陆了没有
    public void jumpWho(Class<?> ac) {
        if (token.isEmpty()) {
            jumpActivity(LoginActivity.class);
        } else {
            jumpActivity(ac);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.re_message:      //交易记录
                if (ids == null || ids.equals("")){
                    jumpWho(LoginActivity.class);
                }else {
                    Intent intent = new Intent(PersonFragment.this.getActivity(), TransactionRecordActivity.class);
                    intent.putExtra("ids", ids);
                    startActivity(intent);
                }
                break;
            case R.id.tabSetting:      //设置
                jumpWho(SettingActivity.class);
                break;
            case R.id.tabCenterTell:   //申诉中心
                jumpWho(SpeakCenterActivity.class);
                break;
            case R.id.tabKeFu:      //客服
                //显示窗口
                callPhoneCur = sp.getString("kefuNumber","");//电话号码
                menuWindowPerKefu = new KehuPopupWindow(PersonFragment.this.getActivity(), itemsOnClick, callPhoneCur);
                menuWindowPerKefu.showAtLocation(PersonFragment.this.getActivity().findViewById(R.id.personZong), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                break;
            case R.id.tabIncome:    //分销返利
                jumpWho(SoldCenterActivity.class);
                break;
            case R.id.tabBlance:    //余额
                jumpWho(BalanceActivity.class);
                break;
            case R.id.tabBindAcount:   //绑定账号
//                jumpWho(BindAcountActivity.class);
                jumpWho(BindKaActivity.class);
                break;
            case R.id.tabChangeInfo:   //修改资料
                jumpWho(MyInfoActivity.class);
                break;
        }
    }


    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindowPerKefu.dismiss();
            switch (v.getId()) {
                case R.id.btnKefu:
                    dialPhone();//打电话
                    break;
                default:
                    break;
            }
        }
    };

    //创建拨打电话
    private void dialPhone() {
        if (!TextUtils.isEmpty(callPhoneCur)) {
            //用intent启动拨打电
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + callPhoneCur));
            if (ActivityCompat.checkSelfPermission(PersonFragment.this.getActivity(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                showToast("权限被拒绝!");
                return;
            }
            try {
                PersonFragment.this.getActivity().startActivity(intent);
            } catch (Exception e) {
                showToast("权限被拒绝!");
            }
        }
    }

    @Override
    public void onResume() {
        //没有数据时不执行startPlaying,避免执行几次导致轮播混乱
        if (mAutoPlayInfoList != null && !mAutoPlayInfoList.isEmpty()) {
            mAutoPlayingViewPager.startPlaying();
        }
        super.onResume();
        if (token != null && token.length() != 0) {
            initScan();
        }
    }

    @Override
    public void onPause() {
        if (mAutoPlayInfoList != null && !mAutoPlayInfoList.isEmpty()) {
            mAutoPlayingViewPager.stopPlaying();
        }
        super.onPause();
    }
}
